package com.sina.auto.components.AddContentImpl;

import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import static java.awt.Color.black;

public class ImageUtil {

    static class MergeImage{
        /**
         * @param files 获取一个缓冲图片数组
         * @param type  拼接方式，1为水平，2为垂直
         * @return
         */
        static BufferedImage mergeImage(BufferedImage[] files, int type) {
            int len = files.length;
            if (len < 1) {
                throw new RuntimeException("图片数量小于1");
            }
            //File[] src = new File[len];
            BufferedImage[] images = new BufferedImage[len];
            int[][] imageArrays = new int[len][];
            for (int i = 0; i < len; i++) {
                images[i] = files[i];
                int width = images[i].getWidth();
                int height = images[i].getHeight();
                imageArrays[i] = new int[width * height];
                imageArrays[i] = images[i].getRGB(0, 0, width, height, imageArrays[i], 0, width);
            }
            int newHeight = 0;
            int newWidth = 0;
            for (BufferedImage image : images) {
                // 横向
                if (type == 1) {
                    newHeight = newHeight > image.getHeight() ? newHeight : image.getHeight();
                    newWidth += image.getWidth();
                } else if (type == 2) {// 纵向
                    newWidth = newWidth > image.getWidth() ? newWidth : image.getWidth();
                    newHeight += image.getHeight();
                }
            }

            // 生成新图片
            return generateNewImage(type, images, imageArrays, newHeight, newWidth);
        }

        //拼接图片后生成一张完整的新图片
        private static BufferedImage generateNewImage(int type, BufferedImage[] images, int[][] imageArrays, int newHeight, int newWidth) {
            try {
                BufferedImage ImageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                int height_i = 0;
                int width_i = 0;
                for (int i = 0; i < images.length; i++) {
                    if (type == 1) {
                        ImageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, imageArrays[i], 0,
                                images[i].getWidth());
                        width_i += images[i].getWidth();
                    } else if (type == 2) {
                        ImageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), imageArrays[i], 0, newWidth);
                        height_i += images[i].getHeight();
                    }
                }
                //输出想要的图片
                return ImageNew;

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 图片拉伸：将模板中间文本区拉伸，与模板上沿和模板下沿拼接。读取本地的一张图片并处理。
     * @param filePath
     * @param x
     * @param y
     * @return
     * @throws Exception
     */
    static BufferedImage imageStretch(String filePath, int x, int y) throws Exception{
            BufferedImage img = ImageIO.read(new File(filePath));
            BufferedImage newIMG = new BufferedImage(x, y, img.getType());
            Graphics g = newIMG.getGraphics();
            //获取指定尺寸的图片
            g.drawImage(img,0,0,x,y,null);
            g.dispose();
            img = newIMG;
            return img;
        }

        //传入一个缓冲图片对象，进行拉伸处理
        static BufferedImage imageStretch(BufferedImage bufferedImage, int x, int y)throws Exception{
            BufferedImage img = bufferedImage;
            BufferedImage newIMG = new BufferedImage(x, y, img.getType());
            Graphics g = newIMG.getGraphics();
            //获取指定尺寸的图片
            g.drawImage(img,0,0,x,y,null);
            g.dispose();
            img = newIMG;
            return img;

    }

    //图片读取操作：BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
    /**
     * 在处理的过程中发现的另外一个问题是：在一张图像中，（0,0）坐标是在图像的左上角，
     * 往下是height的增方向，往右是weight的增方向，即在图像的右下角的坐标值是（height-1，weight-1）
     * ，这跟传统意义上的坐标轴的方向是不一样的，这点需要特别注意。
     */
    public static BufferedImage[] imageCut(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        BufferedImage image = ImageIO.read(fis); //把文件读到图片缓冲流中

        int rows = 3; //纵向切块数量
        int cols = 1;//横向切块数量
        int chunks = rows * cols;

        int chunkWidth = image.getWidth() / cols; // 计算每一块小图片的高度和宽度
        int chunkHeight = image.getHeight() / rows;
        int count = 0;
        BufferedImage imgs[] = new BufferedImage[chunks];
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                //初始化BufferedImage
                imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

                //画出每一小块图片
                Graphics2D gr = imgs[count++].createGraphics();
                gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
                gr.dispose();
            }
        }
        System.out.println("切分完成");
        System.out.println("小图片创建完成");
        return imgs;
    }

    //计算一个字符串根据每行宽度width换行后的行数
    static int contentHeight(int lineNum, int strHeight,int timeHeight, int RowSpacing){
        return (lineNum * strHeight) + 70 + timeHeight + RowSpacing;
    }

    //返回一个字符串的像素宽度
    static int fontWidth(Font font, String content){
        FontMetrics fm = FontDesignMetrics.getMetrics(font);
        return fm.stringWidth(content);
    }

    static int fontHeight(Font font){
        FontMetrics fm = FontDesignMetrics.getMetrics(font);
        return fm.getHeight();
    }

    //将整个字符串根据图片的宽度写成数组
    static void stringHeight(String content, FontMetrics metrics, int realWidth, StringBuilder sb, int j, int tempStart, String[] tempStrings, String[] extendTemp) {
        for(int i1 =0;i1<content.length();i1++){
            char ch = content.charAt(i1);
            sb.append(ch);
            Rectangle2D bounds2 = metrics.getStringBounds(sb.toString(), null);
            int tempStrPi1exlWi1dth = (int) bounds2.getWidth();
            if(tempStrPi1exlWi1dth > realWidth){
                tempStrings[j++] = content.substring(tempStart,i1);
                tempStart = i1;
                sb.delete(0, sb.length());
                sb.append(ch);
            }
            if(i1 ==  content.length()-1) {
                //最后一行
                if (j == tempStrings.length) {
                    for (int k = 0; k < tempStrings.length; k++) {
                        extendTemp[k] = tempStrings[k];
                    }
                    extendTemp[j] = content.substring(tempStart);
                } else {
                    tempStrings[j] = content.substring(tempStart);
                    break;
                }
            }
        }
    }

    //绘制时间（添加作者）
    static void drawTime(int width, Font timeFont, BufferedImage image, String author, int startHeight) {
        //获得画笔，绘制时间
        Graphics2D DrawTime = image.createGraphics();

        DrawTime.setFont(timeFont);
        DrawTime.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        DrawTime.setColor(black);
        DrawTime.drawImage(image, 0, 0, null);
        //打印时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeString = df.format(new Date()) + " " + author;
        DrawTime.drawString(timeString, (width - fontWidth(timeFont,timeString)) / 2, startHeight);
        DrawTime.dispose();
    }

    //绘制时间（不添加作者）
    static void drawTime(int width, Font timeFont, BufferedImage image, int startHeight) {
        //获得画笔，绘制时间
        Graphics2D DrawTime = image.createGraphics();

        DrawTime.setFont(timeFont);
        DrawTime.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        DrawTime.setColor(black);
        DrawTime.drawImage(image, 0, 0, null);
        //打印时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeString = df.format(new Date());
        DrawTime.drawString(timeString, (width - fontWidth(timeFont,timeString)) / 2, startHeight);
        DrawTime.dispose();
    }

    //绘制标题
    static void drawTitle(int width, Font titleFont, BufferedImage image, String title, int startHeight) {
        //获得画笔，绘制标题
        Graphics2D drawTitle = image.createGraphics();

        drawTitle.setFont(titleFont);
        drawTitle.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        drawTitle.setColor(black);
        drawTitle.drawImage(image, 0, 0, null);
        drawTitle.drawString(title, (width - fontWidth(titleFont,title)) / 2, startHeight);
        drawTitle.dispose();
    }

    //核心：循环绘制正文内容，自动换行
    static void drawContent(int rowSpacing, Font contentFont, int width, int startHeight, Graphics2D g2, String[] tempStrings, String[] extendTemp) {
        if (extendTemp[0] == null) {
            for (int count = 0; count < tempStrings.length; count++) {
                int drawHeight = startHeight + (fontHeight(contentFont) + rowSpacing) * count;
                g2.drawString(tempStrings[count], (int) (width / 9.8), drawHeight);
            }
        } else {
            for (int count = 0; count < extendTemp.length; count++) {
                int DrawHeight = startHeight + (fontHeight(contentFont) + rowSpacing) * count;
                g2.drawString(extendTemp[count], (int) (width / 9.8), DrawHeight);
            }
        }
    }

}
